//
//  ListInstitutionsViewController.m
//  Edumap
//
//  Created by 辰领科技 on 16/7/21.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "ListInstitutionsViewController.h"
#import "LeftTableViewCell.h"
#import "RightTableViewCell.h"

#import "AgencyDetailsViewController.h"
#import "CourseDetailsViewController.h"

static NSString *leftCellIdentifier = @"LeftTableViewCell";
static NSString *rightCellIdentifier = @"RightTableViewCell";

@interface ListInstitutionsViewController ()
<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UILabel *titleLabel;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *LeftTableView;
@property (strong, nonatomic) IBOutlet UITableView *RightTableView;

@property (assign, nonatomic) NSInteger count;

@property (strong, nonatomic) NSMutableArray *leftInstitutionsArray;
@property (strong, nonatomic) NSMutableArray *rightInstitutionsArray;
@property (strong, nonatomic) NSMutableArray *leftcourseArray;
@property (strong, nonatomic) NSMutableArray *rightcourseArray;
@property (weak, nonatomic) IBOutlet UITextField *searchField;

@end

@implementation ListInstitutionsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.count = 0;
    
    if (_isListInstitutions) {
        self.titleLabel.text = @"机构列表";
        [self ClassificationOfInstitutions];
    } else {
        self.titleLabel.text = @"课程列表";
        [self ClassificationOfCourse];
    }
    [self.RightTableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _rightInstitutionsArray = [NSMutableArray array];
    _rightcourseArray = [NSMutableArray array];
    _pageNO = 1;
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    _searchField.layer.cornerRadius = 4*VerticalRatio();
    _searchField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 1)];
    _searchField.leftViewMode = UITextFieldViewModeAlways;
    
    [self.LeftTableView registerNib:[UINib nibWithNibName:leftCellIdentifier bundle:nil] forCellReuseIdentifier:leftCellIdentifier];
    self.LeftTableView.delegate = self;
    self.LeftTableView.dataSource = self;
    self.LeftTableView.backgroundColor = [UIColor colorWithWhite:0.957 alpha:1.000];
    
    [self.RightTableView registerNib:[UINib nibWithNibName:rightCellIdentifier bundle:nil] forCellReuseIdentifier:rightCellIdentifier];
    self.RightTableView.delegate = self;
    self.RightTableView.dataSource = self;
    
    _searchField.delegate = self;
}



- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark - 搜索
- (IBAction)search:(UIButton *)sender {
    if (_searchField.hidden == YES) {
        _searchField.hidden = NO;
    }else{
        if (_searchField.text.length>0) {
            [self.RightTableView.header beginRefreshing];
        }else{
        _searchField.hidden = YES;
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self hideKeyBoard];
    [self.RightTableView.header beginRefreshing];
    return YES;
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.RightTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.RightTableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            if (_isListInstitutions) {
                [self ListOfInstitutions];
            }else{
                [self CourseList];
            }
        });
        
    }];
    // 马上进入刷新状态
    [self.RightTableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    NSMutableArray * array = [NSMutableArray array];
    if (_isListInstitutions) {
        array = _rightInstitutionsArray;
    }else{
        array = _rightcourseArray;
    }
    
    if (array.count == _totle) {
        [self.RightTableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            if (_isListInstitutions) {
                [self ListOfInstitutions];
            }else{
                [self CourseList];
            }
        });
    }
    
}




#pragma mark - 获取机构分类
- (void)ClassificationOfInstitutions {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallStoreTypeList withHttpType:@"POST" withTag:JY_JY_mallStoreTypeList];
}

#pragma mark - 获取机构列表
- (void)ListOfInstitutions {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    if (_count != 0) {
        [dic setObject:self.leftInstitutionsArray[self.count][@"mstyId"] forKey:@"mstoTypeOne"];
    }
    
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"] forKey:@"lat"];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lng"] forKey:@"lng"];
    [dic setObject:_searchField.text forKey:@"mstoName"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallStoreList withHttpType:@"POST" withTag:JY_JY_mallStoreList];
}

#pragma mark - 获取课程分类
- (void)ClassificationOfCourse {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallGoodsTypeList withHttpType:@"POST" withTag:JY_JY_mallGoodsTypeList];
}

#pragma mark - 获取课程列表
- (void)CourseList {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    if (_count != 0) {
        [dic setObject:self.leftcourseArray[self.count][@"mgtyId"] forKey:@"mgooTypeId"];
    }
    [dic setObject:_searchField.text forKey:@"mstoName"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallGoodsList withHttpType:@"POST" withTag:JY_JY_mallGoodsList];
}

#pragma mark - <UITableViewDelegate && UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == _LeftTableView) {
        if (_isListInstitutions) {
            return self.leftInstitutionsArray.count;
        } else {
            return self.leftcourseArray.count;
        }
        
    } else {
        if (_isListInstitutions) {
           return self.rightInstitutionsArray.count;
        } else {
            return self.rightcourseArray.count;
        }
    }
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _LeftTableView) {
        
        return 45*VerticalRatio();
    } else {
        
        return 90*VerticalRatio();
    }
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == _LeftTableView) {
        LeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:leftCellIdentifier];
        
        if (cell == nil) {
            cell= [[LeftTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:leftCellIdentifier];
        }
        
        cell.backgroundColor = [UIColor colorWithWhite:0.957 alpha:1.000];
        cell.label.textColor = [UIColor colorWithWhite:0.290 alpha:1.000];
        if (_count == indexPath.row) {
            cell.backgroundColor = [UIColor whiteColor];
            cell.label.textColor = [UIColor colorWithRed:0.086 green:0.306 blue:0.529 alpha:1.000];
        }
        
        cell.label.frame = flexibleFrame(CGRectMake(3, 0, 63, 0), NO);
        cell.label.numberOfLines = 0;
        if (_isListInstitutions) {
            cell.label.text = self.leftInstitutionsArray[indexPath.row][@"mstyName"];
        } else {
            cell.label.text = self.leftcourseArray[indexPath.row][@"mgtyName"];
        }
        [cell.label sizeToFit];
        cell.label.center = CGPointMake(35*VerticalRatio(), 23*VerticalRatio());
        
        return cell;
    } else {
        
        RightTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:rightCellIdentifier];
        if (cell == nil) {
            cell= [[RightTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:rightCellIdentifier];
        }
        
        if (_isListInstitutions) {
            cell.detailLabel.hidden = NO;
            cell.distanceLabel.hidden = NO;
            cell.moneyLabel.hidden = YES;
            cell.contentLabel.hidden = YES;
            
            NSString *image = [NSString stringWithFormat:@"%@",self.rightInstitutionsArray[indexPath.row][@"mstoImage"]];
            if (image && image.length>0 && ![self.rightInstitutionsArray[indexPath.row][@"mstoImage"] isEqual:[NSNull null]]) {
                [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
            }
            cell.titleLabel.text = [NSString stringWithFormat:@"%@",self.rightInstitutionsArray[indexPath.row][@"mstoName"]];
            cell.detailLabel.text = [NSString stringWithFormat:@"%@",self.rightInstitutionsArray[indexPath.row][@"mstoContent"]];
            
            CGFloat distance = [self.rightInstitutionsArray[indexPath.row][@"distance"]floatValue];
            if (distance<1000) {
                [cell.distanceLabel setTitle:[NSString stringWithFormat:@" 距离%dm",(NSInteger)distance] forState:UIControlStateNormal];
            }else{
                [cell.distanceLabel setTitle:[NSString stringWithFormat:@" 距离%.1fkm",distance/1000] forState:UIControlStateNormal];
            }

        } else {
            cell.detailLabel.hidden = YES;
            cell.distanceLabel.hidden = YES;
            cell.moneyLabel.hidden = NO;
            cell.contentLabel.hidden = NO;
            
            NSString *image = [NSString stringWithFormat:@"%@",self.rightcourseArray[indexPath.row][@"mgooImage"]];
            if (image && image.length>0 && ![self.rightcourseArray[indexPath.row][@"mgooImage"] isEqual:[NSNull null]]) {
                [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
            }
            cell.titleLabel.text = [NSString stringWithFormat:@"%@",self.rightcourseArray[indexPath.row][@"mgooName"]];
            cell.moneyLabel.text = [NSString stringWithFormat:@"￥%@",self.rightcourseArray[indexPath.row][@"mgooPrice"]];
            cell.contentLabel.text = [NSString stringWithFormat:@"%@",self.rightcourseArray[indexPath.row][@"mgooContext"]];
        }
        
        return cell;
    }
    
}


//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _LeftTableView) {
        _count = indexPath.row;
        if (self.isListInstitutions) {
            [self ListOfInstitutions];
        } else {
            [self.RightTableView.header beginRefreshing];
        }
        [self.LeftTableView reloadData];
        [self.RightTableView reloadData];
    } else {
        if (self.isListInstitutions) {

            //机构详情
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
            AgencyDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AgencyDetails"];
            
            page.mstoId = self.rightInstitutionsArray[indexPath.row][@"mstoId"];
            page.backBlock = ^(){};
            [[Common getNavigation] pushViewController:page];
        } else {
            
            //课程详情
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
            CourseDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"CourseDetails"];
            
            page.mgooId = self.rightcourseArray[indexPath.row][@"mgooId"];
            page.mstoId = self.rightcourseArray[indexPath.row][@"mgooStoreId"];
            
            [[Common getNavigation] pushViewController:page];
        }
    }
    
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_RightTableView.header endRefreshing];
    [_RightTableView.header endRefreshing];
    if (tag==JY_JY_mallStoreTypeList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.leftInstitutionsArray = [NSMutableArray array];
            self.leftInstitutionsArray = database[@"result"];
            NSDictionary *dic =@{@"mstyName":@"全部分类"};
            [self.leftInstitutionsArray insertObject:dic atIndex:0];
            if (_count == 0) {
                [self ListOfInstitutions];
            }
            [self.LeftTableView reloadData];
        }
    } else if (tag==JY_JY_mallStoreList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.RightTableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.RightTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.rightInstitutionsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.rightInstitutionsArray addObject:entity];
                }
                [_RightTableView reloadData];
                
            });
            

        }
        
    } else if (tag==JY_JY_mallGoodsTypeList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.leftcourseArray = [NSMutableArray array];
            self.leftcourseArray = database[@"result"];
            NSDictionary *dic =@{@"mgtyName":@"全部分类"};
            [self.leftcourseArray insertObject:dic atIndex:0];
            if (self.count == 0) {
                [self addRefreshing];
            }
            [self.LeftTableView reloadData];
        }
        
    } else if (tag==JY_JY_mallGoodsList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.RightTableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.RightTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.rightcourseArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.rightcourseArray addObject:entity];
                }
                [_RightTableView reloadData];
                
            });
        }
        
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_RightTableView.header endRefreshing];
    [_RightTableView.header endRefreshing];
    [self dismissWaitDialog];
    
}





@end
